<template>
  <div>
    <table-wrap :allList="allList" class="monitor-table" ref="tableWrap" :tr-height="trHeight">
      <template slot="thead">
        <th v-for="item in headOptionsNoShow" :key="item.name" :class="{ ascending: (item.name === sortObj.name)&&(sortObj.type === 'up'),descending: (item.name === sortObj.name)&&(sortObj.type === 'down') }">
          <div class="cell" @click.stop="sort(item.name)">{{item.displayname}}
            <span class="caret-wrapper" v-if="item.name !== 'answerStyle'" >
            <i class="sort-caret ascending"></i><i class="sort-caret descending"></i>
            </span>
          </div>
        </th>
        <th v-for="item in header" :key="item.name" v-show="item.show === true" :class="{ ascending: (item.name === sortObj.name)&&(sortObj.type === 'up'),descending: (item.name === sortObj.name)&&(sortObj.type === 'down') }">
          <div class="cell" @click="sort(item.name)">{{item.displayname}}
            <span class="caret-wrapper" v-if="!(item.name === 'answerCount'|| item.name === 'sensitiveWord' ||item.name === 'dialoutCount'||item.name === 'stateSwitch')">
            <i class="sort-caret ascending"></i><i class="sort-caret descending"></i>
            </span>
          </div>
        </th>
        <th><div class="cell">{{$t('monitor.operate')}}</div></th>
      </template>
      <template slot="tbody" slot-scope="slotProps">
        <tr-agent
          v-if="phonePeers[one]"
          :one="phonePeers[one]"
          v-for="(one, index) in slotProps.current"
          :key="one"
          ref="trAgent"
          :monitorHeader="header"
          @ctiUiListen="ctiUiListen"
          @ctiUiEndListen="ctiUiEndListen"
          @ctiUiForceHangup="ctiUiForceHangup"
          @ctiUiLoot="ctiUiLoot"
          @ctiUiKick="ctiUiKick"
          @ctiUiPick="ctiUiPick"
        ></tr-agent>
      </template>
    </table-wrap>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('public.tip')" :visible.sync="dialogFormVisible">
      <div class="moniter-dialog">
        <div class="dialog-title">{{$t('monitor.noCheckIn')}}</div>
        <el-row :gutter="15">
          <el-col :span="20">
            <el-form :model="form" :label-position="'left'" :rules="rules" ref="form" label-width="180px">
              <el-form-item :label="formLabel" prop="mobile">
                <el-input size="mini" v-model.trim="form.mobile" auto-complete="off"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="4"></el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" type="warning" @click="saveLocalNumForPhonePick">{{$t('monitor.saveAndCheckIn')}}</el-button>
        <el-button class="primary_btn" @click="dialogFormVisible = false">{{$t('public.cancel')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import tableWrap from './tableWrapAgent'
  import trAgent from './TrAgent'
  import {checkform} from '@/utils/validate'
  import bus from '@/store/eventBus'
  export default {
    name: 'callMonitor',
    data () {
      let validate1 = (rule, value, callback) => {
        let match = checkform(value, 'Number')
        if (match) {
          callback(new Error(this.$t(match)))
        } else {
          callback()
        }
      }
      return {
        headOptionsNoShow: [{'name': 'agentName', displayname: this.$t('public.agent'), 'order': 1, 'show': true}, {'name': 'agentNo', displayname: this.$t('public.jobNumber'), 'order': 2, 'show': true}, {'name': 'version', displayname: this.$t('monitor.agentVersion'), 'order': 1, 'show': true}, {'name': 'answerStyle', displayname: this.$t('monitor.answerMode'), 'order': 3, 'show': true}, {'name': 'state', displayname: this.$t('public.state'), 'order': 4, 'show': true}],
        dialogFormVisible: false,
        formLabel: '',
        form: {
          _id: '',
          mobile: ''
        },
        sortObj: {
          name: '',
          type: '',
          num: 0
        },
        rules: {
          mobile: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'},
            {validator: validate1, trigger: 'blur'}
          ]
        },
        trHeight: 53
      }
    },
    props: {
      allList: {
        type: Array,
        default: function () {
          return []
        }
      },
      header: {
        type: Array,
        default: function () {
          return []
        }
      },
      cacheAgent: {
        type: Array,
        default: function () {
          return []
        }
      }
    },
    components: {
      tableWrap,
      trAgent
    },
    computed: {
    },
    inject: ['phonePeers', 'init'],
    watch: {
      header () {
        // 表头高度发生变化，重置tbody高度
        this.resize()
      }
    },
    methods: {
      // 操作：监听
      ctiUiListen (data) {
        let peer = window.phone_peers[data.userId]
        if (peer == null) {
          this.$message.error(this.$t('cti.chanSpyFailed'))
          return
        }
        if (this.$store.state.cti.globalLet.phone_data.busyType === '0') {
          this.$message.error(this.$t('cti.configPhoneBusy'))
          return
        }
        if (this.$store.state.cti.globalLet.phone_data.extenType === 'none') {
          this.$message.error(this.$t('cti.spyWithLoginTypes'))
          return
        }
        if (peer.userId === this.$store.state.cti.globalLet.phone_data.userId) {
          this.$message.error(this.$t('cti.noSpyUserSelf'))
          return
        }
        if (peer.callStatus !== 'webcall' && peer.callStatus !== 'inner' &&
          peer.callStatus !== 'normal' && peer.callStatus !== 'dialout' &&
          peer.callStatus !== 'dialTransfer' && peer.callStatus !== 'transfer') {
          this.$message.error(this.$t('cti.statusForbidSpy'))
          return
        }
        this.$store.dispatch('phoneListen', data.channel).then((response) => {
          this.phonePeers[data.userId].operate.buttonState.listen = {disabled: true, show: false}
          this.phonePeers[data.userId].operate.buttonState.loot = {disabled: true, show: false}
        })
      },
      // 操作：结束监听
      ctiUiEndListen (data) {
        this.$store.dispatch('phoneHangup').then((response) => {
          this.phonePeers[data.userId].operate.buttonState.listen = {disabled: false, show: true}
          this.phonePeers[data.userId].operate.buttonState.loot = {disabled: false, show: true}
        })
      },
      // 操作：强拆
      ctiUiForceHangup (data) {
        if (data.pbx === this.$store.state.cti.globalLet.phone_data.pbx_in_ip) {
          this.$store.dispatch('phoneHangupChannel', data.channel).then((response) => {
          })
        } else {
          this.$store.dispatch('phoneHangupChannelFromPbx', data).then((response) => {
          })
        }
      },
      // 操作：抢接
      ctiUiLoot (data) {
        this.$store.dispatch('phoneLoot', data.linkedChannel).then((response) => {
        })
      },
      // 操作：签出
      ctiUiKick (data) {
        this.$store.dispatch('phoneKick', data.userId).then((response) => {
        })
      },
      // 操作：签入手机或sip话机
      ctiUiPick (data, extenType) {
        let dataPick = {
          userId: data.userId,
          extenType: extenType
        }
        this.$store.dispatch('phonePick', dataPick).then((response) => {
          if (response != null && !response.Local) {
            let userInfo = window.phone_peers[data.userId]
            let name = userInfo.DisplayName + '[' + userInfo.exten + ']'
            this.formLabel = this.$t('monitor.setNumber', {name})
            this.form._id = data.userId
            this.form.mobile = ''
            this.dialogFormVisible = true
          }
        })
      },
      saveLocalNumForPhonePick () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$store.dispatch('saveLocalNumForPhonePick', this.form).then((response) => {
              this.dialogFormVisible = false
              this.form._id = ''
              this.form.mobile = ''
            })
          }
        })
      },
      // 排序
      sort (name) {
        if (name === 'answerStyle' || name === 'answerCount' || name === 'dialoutCount' || name === 'stateSwitch') {
          return
        }
        if (this.sortObj.name !== name) {
          this.sortObj.num = 0
        }
        this.sortObj.name = name
        if (this.sortObj.num % 2) {
          this.sortObj.type = 'down'
        } else {
          this.sortObj.type = 'up'
        }
        this.sortObj.num++
        this.cacheAgent.sort((a, b) => {
          if (this.sortObj.type === 'down') {
            return this.sortMethod(this.phonePeers[a._id], this.phonePeers[b._id], this.sortObj.name)
          } else {
            return this.sortMethod(this.phonePeers[b._id], this.phonePeers[a._id], this.sortObj.name)
          }
        })
      },
      sortMethod (a, b, name, type) {
        let x = ''
        let y = ''
        if (name === 'state') {
          if (a && a.state.content) {
            x = a.state.content.replace(/\s+/g, '')
          }
          if (b && b.state.content) {
            y = b.state.content.replace(/\s+/g, '')
          }
        } else {
          x = a[name]
          y = b[name]
        }
        if (name === 'agentName' || name === 'customerNo' || name === 'queueName' || name === 'state' || name === 'version') {
          return x.localeCompare(y)
        } else {
          return x - y
        }
      },
      callMonitorRefresh () {
        // 其他模块切换到通话监控，重新计算高度
        this.$refs.tableWrap && this.$refs.tableWrap.handleScroll()
        this.resize()
      },
      resize () {
        // 页面大小发上变化，重新计算高度
        this.$nextTick(() => {
          this.$refs.tableWrap && this.$refs.tableWrap.fixed()
          if (this.$refs.trAgent && this.$refs.trAgent.length) {
            this.trHeight = this.$refs.trAgent[0].$el.offsetHeight || 53
          }
        })
      },
      getepigraph () {
        this.$store.dispatch('getMonitorSensitiveWordsHistory', {})
      }
    },
    beforeMount () {
      bus.$on('monitor:callMonitorRefresh', this.callMonitorRefresh)
      window.addEventListener('resize', this.resize)
    },
    beforeDestroy () {
      bus.$off('monitor:callMonitorRefresh', this.callMonitorRefresh)
      window.removeEventListener('resize', this.resize)
    },
    mounted () {
      this.getepigraph()
    }
  }
</script>
<style lang="stylus" scoped>
</style>
